var io      = require('socket.io'),
    http    = require('http'),
    express = require('express');
var path = require('path');
//var log4js = require("log4js")

var PORT = process.env.PORT || 8080,
    HOST = process.env.HOST || 'localhost';
var RedisStore = require('connect-redis')(express);
var fs = require("fs");

// We define the key of the cookie containing the Express SID
var EXPRESS_SID_KEY = 'express.sid';

// We define a secret string used to crypt the cookies sent by Express
var COOKIE_SECRET = 'very secret string';
var cookieParser = express.cookieParser(COOKIE_SECRET);

// Create a new store in memory for the Express sessions
var sessionStore = new RedisStore({
    host: '127.0.0.1',
    port: 6379,
    ttl: 30,
    prefix: 'settings.redisPrefix',
    db: 'mydb'})
var SECRET=COOKIE_SECRET
var app = express();
//var logger = log4js.getLogger('normal');
//logger.setLevel('INFO');
// Configure Express app with :
// * Cookie Parser created above
// * Configure Session Store
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.json());
app.use(express.urlencoded());
app.use(express.methodOverride());
app.configure(function () {
    app.use(cookieParser);
    app.use(express.session({
        store: sessionStore,
        secret: SECRET ,
        cookie: {
            httpOnly: true
        },
        key: EXPRESS_SID_KEY
    }));
});
app.use(express.static(path.join(__dirname, 'public')));

// Configture routes
app.get('/', function (req, res) {
    res.redirect(__dirname + 'index.html');
});
app.all('/*', function (req, res) {
    console.log(req.session)
});


// Create HTTP server, register socket.io as listener
server = http.createServer(app);
io = io.listen(server,{log:false});

// We configure the socket.io authorization handler (handshake)
io.set('authorization', function (data, callback) {
    if(!data.headers.cookie) {
        return callback('No cookie transmitted.', false);
    }

    // We use the Express cookieParser created before to parse the cookie
    // Express cookieParser(req, res, next) is used initialy to parse data in "req.headers.cookie".
    // Here our cookies are stored in "data.headers.cookie", so we just pass "data" to the first argument of function
    cookieParser(data, {}, function(parseErr) {
        if(parseErr) { return callback('Error parsing cookies.', false); }

        // Get the SID cookie
        var sidCookie = (data.secureCookies && data.secureCookies[EXPRESS_SID_KEY]) ||
            (data.signedCookies && data.signedCookies[EXPRESS_SID_KEY]) ||
            (data.cookies && data.cookies[EXPRESS_SID_KEY]);

        // Then we just need to load the session from the Express Session Store
        sessionStore.load(sidCookie, function(err, session) {
            // And last, we check if the used has a valid session and if he is logged in
            if (err || !session || session.mainInfo == null || session.mainInfo == undefined|| session.mainInfo == "") {
                callback('Not logged in.', false);
            } else {
                // If you want, you can attach the session to the handshake data, so you can use it again later
                // You can access it later with "socket.handshake.session"
                data.session = session;

                callback(null, true);
            }
        });
    });
});

// upon connection, start a periodic task that emits (every 1s) the current timestamp
io.sockets.on('connection', function (socket) {
    var session = socket.handshake.session;
    var room = session.mainInfo.group;
    var uname = session.mainInfo.uname;
    var uid=session.mainInfo.uid;
    socket.join(room);
    fs.readFile("./chat_record/"+room+"_"+getNowFormatDate(),'utf-8',function(err,data){
        var datas =[];
        if(data != undefined && data != ""){
            datas = data.split('\n');
        }
        var data_res = ""
        for(var i=datas.length-1,j=0;i> 0 && j<=10;i--,j++){
            var datas2 ;
            if(datas[i] != undefined && datas[i] != ""){
                datas2= datas[i].split('&&');
                data_res+=datas2[0]+" = "+datas2[2]+" = "+datas2[1]+"<br>"
            }
        }
        socket.emit("data",data_res)
    })
    socket.on("to",function(data){
        fs.appendFile("./chat_record/"+room+"_"+getNowFormatDate(),data.text+"&& "+getNowFormatTime()+" && "+uname+" && "+uid+"\n",'utf-8',function(err){
            if(err) throw err;
        })
        socket.emit('news',data.text+"   "+uname+" "+getNowFormatTime()+"<br>" );
        socket.broadcast.to(room).emit('news', data.text+"    "+uname+" "+getNowFormatTime()+"<br>");
    })
    socket.on("file",function(data){
        console.log(data)
    })
    socket.on("disconnect",function(){
        console.log(uname+"  退出了")
        socket.emit('news',uname+"  退出了<br>" );
        socket.broadcast.to(room).emit('news',uname+"  退出了<br>");
    })
});

server.listen(PORT, null, function() {
    console.log('Server listening on port %d in %s mode', this.address().port, app.settings.env);
});

getNowFormatDate=function ()
{
    var day = new Date();
    var Year = 0;
    var Month = 0;
    var Day = 0;
    var CurrentDate = "";
//初始化时间
//Year= day.getYear();//有火狐下2008年显示108的bug
    Year= day.getFullYear();//ie火狐下都可以
    Month= day.getMonth()+1;
    Day = day.getDate();
//Hour = day.getHours();
// Minute = day.getMinutes();
// Second = day.getSeconds();
    CurrentDate += Year + "-";
    if (Month >= 10 )
    {
        CurrentDate += Month + "-";
    }
    else
    {
        CurrentDate += "0" + Month + "-";
    }
    if (Day >= 10 )
    {
        CurrentDate += Day ;
    }
    else
    {
        CurrentDate += "0" + Day ;
    }
    return CurrentDate;
}
/**
 * 获取当前日期 时间
 * @returns {string}
 */
getNowFormatTime=function ()
{
    var day = new Date();
    var Year = 0;
    var Month = 0;
    var Day = 0;
    var Hour,Minute,Second;
    var CurrentDate = "";
//初始化时间
//Year= day.getYear();//有火狐下2008年显示108的bug
    Year= day.getFullYear();//ie火狐下都可以
    Month= day.getMonth()+1;
    Day = day.getDate();
    Hour = day.getHours();
    Minute = day.getMinutes();
    Second = day.getSeconds();
    CurrentDate += Year + "-";
    if (Month >= 10 )
    {
        CurrentDate += Month + "-";
    }
    else
    {
        CurrentDate += "0" + Month + "-";
    }
    if (Day >= 10 )
    {
        CurrentDate += Day ;
    }
    else
    {
        CurrentDate += "0" + Day ;
    }
    return CurrentDate+" "+Hour+":"+Minute+":"+Second;
}